/**
 * 图片优化工具
 * 提供图片压缩、格式转换、尺寸调整等功能
 */

/**
 * 检测浏览器是否支持 WebP
 * @returns {Promise<boolean>}
 */
export async function supportsWebP() {
  if (typeof window === 'undefined') return false
  
  // 检查是否已经缓存结果
  if (window.__webpSupport !== undefined) {
    return window.__webpSupport
  }

  const webpData = ''
  
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = img.onerror = () => {
      window.__webpSupport = img.width === 1
      resolve(window.__webpSupport)
    }
    img.src = webpData
  })
}

/**
 * 将图片转换为 WebP 格式
 * @param {File|Blob} file - 原始图片文件
 * @param {number} quality - 质量 (0-1)
 * @returns {Promise<Blob>}
 */
export async function convertToWebP(file, quality = 0.8) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      const img = new Image()
      
      img.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0)
        
        // 转换为 WebP
        canvas.toBlob(
          (blob) => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('Failed to convert to WebP'))
            }
          },
          'image/webp',
          quality
        )
      }
      
      img.onerror = reject
      img.src = e.target.result
    }
    
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * 压缩图片
 * @param {File|Blob} file - 原始图片
 * @param {Object} options - 压缩选项
 * @returns {Promise<Blob>}
 */
export async function compressImage(file, options = {}) {
  const {
    maxWidth = 1920,
    maxHeight = 1080,
    quality = 0.8,
    format = 'image/jpeg'
  } = options

  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      const img = new Image()
      
      img.onload = () => {
        let { width, height } = img
        
        // 计算新尺寸（保持宽高比）
        if (width > maxWidth || height > maxHeight) {
          const aspectRatio = width / height
          
          if (width > height) {
            width = maxWidth
            height = width / aspectRatio
          } else {
            height = maxHeight
            width = height * aspectRatio
          }
        }
        
        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, width, height)
        
        canvas.toBlob(
          (blob) => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('Failed to compress image'))
            }
          },
          format,
          quality
        )
      }
      
      img.onerror = reject
      img.src = e.target.result
    }
    
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * 生成缩略图
 * @param {File|Blob} file - 原始图片
 * @param {number} size - 缩略图尺寸
 * @returns {Promise<string>} - Base64 数据URL
 */
export async function generateThumbnail(file, size = 150) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      const img = new Image()
      
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const aspectRatio = img.width / img.height
        
        let width, height
        if (aspectRatio > 1) {
          width = size
          height = size / aspectRatio
        } else {
          height = size
          width = size * aspectRatio
        }
        
        canvas.width = width
        canvas.height = height
        
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, width, height)
        
        resolve(canvas.toDataURL('image/jpeg', 0.7))
      }
      
      img.onerror = reject
      img.src = e.target.result
    }
    
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * 图片预加载
 * @param {string[]} urls - 图片URL数组
 * @returns {Promise<void>}
 */
export async function preloadImages(urls) {
  const promises = urls.map((url) => {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = resolve
      img.onerror = reject
      img.src = url
    })
  })
  
  try {
    await Promise.all(promises)
    console.log(`[Image Optimizer] Preloaded ${urls.length} images`)
  } catch (error) {
    console.error('[Image Optimizer] Failed to preload some images:', error)
  }
}

/**
 * 获取图片尺寸
 * @param {File|Blob|string} input - 图片文件或URL
 * @returns {Promise<{width: number, height: number}>}
 */
export async function getImageDimensions(input) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    
    img.onload = () => {
      resolve({
        width: img.width,
        height: img.height
      })
    }
    
    img.onerror = reject
    
    if (typeof input === 'string') {
      img.src = input
    } else {
      const reader = new FileReader()
      reader.onload = (e) => {
        img.src = e.target.result
      }
      reader.onerror = reject
      reader.readAsDataURL(input)
    }
  })
}

/**
 * 批量优化图片
 * @param {File[]} files - 图片文件数组
 * @param {Object} options - 优化选项
 * @returns {Promise<Array>} - 优化后的图片数组
 */
export async function optimizeImages(files, options = {}) {
  const optimized = []
  
  for (const file of files) {
    try {
      // 检查是否支持 WebP
      const webpSupported = await supportsWebP()
      
      let optimizedFile = file
      
      // 如果支持 WebP，转换为 WebP
      if (webpSupported && !file.type.includes('webp')) {
        optimizedFile = await convertToWebP(file, options.quality)
      } else {
        // 否则压缩原格式
        optimizedFile = await compressImage(file, options)
      }
      
      // 生成缩略图
      const thumbnail = await generateThumbnail(optimizedFile)
      
      optimized.push({
        original: file,
        optimized: optimizedFile,
        thumbnail,
        saved: file.size - optimizedFile.size,
        compressionRatio: ((1 - optimizedFile.size / file.size) * 100).toFixed(2)
      })
      
      console.log(
        `[Image Optimizer] Optimized ${file.name}: ${(file.size / 1024).toFixed(2)}KB → ${(optimizedFile.size / 1024).toFixed(2)}KB (${optimized[optimized.length - 1].compressionRatio}% saved)`
      )
    } catch (error) {
      console.error(`[Image Optimizer] Failed to optimize ${file.name}:`, error)
      optimized.push({
        original: file,
        optimized: file,
        thumbnail: null,
        error: error.message
      })
    }
  }
  
  return optimized
}

/**
 * 创建响应式图片源集
 * @param {string} baseUrl - 基础URL
 * @param {number[]} sizes - 尺寸数组
 * @returns {string} - srcset 字符串
 */
export function createResponsiveSrcSet(baseUrl, sizes = [320, 640, 1024, 1920]) {
  return sizes
    .map((size) => `${baseUrl}?w=${size} ${size}w`)
    .join(', ')
}

// 默认导出所有工具
export default {
  supportsWebP,
  convertToWebP,
  compressImage,
  generateThumbnail,
  preloadImages,
  getImageDimensions,
  optimizeImages,
  createResponsiveSrcSet,
}

